import { AppStore, PagingInfo } from './../../services/appStore';
import { Component, Input, Inject, ElementRef, ChangeDetectorRef, trigger, animate, transition, style, state, EventEmitter, Output } from '@angular/core';
@Component({
    selector: 'x-scrollable-container',
    styleUrls: ['./scrollable-container.scss'],
    template: `
        <div class='x-scrollable-container' style="overflow-x: scroll;height:100%;width:100%;flex-wrap:wrap;display: flex; flex-direction:column ;justify-content: flex-start;align-content: flex-start;" list>
            <ng-content></ng-content>
            <div blank></div>
        </div>
    `
})
export class XScrollableContainer {
    constructor(private element: ElementRef, private changeDetectorRef: ChangeDetectorRef) {
    }
    lastScrollLeft = 0;

    @Output() change = new EventEmitter();

    childrenChanged() {
        this.autoCompleteBlank();
        this.turningPage(0);
    }

    ngAfterViewInit() {
    }

    private turningPage(count: number) {
        //todo 优化
        const list = this.element.nativeElement.querySelector("[list]");
        if (!list) return;
        list.scrollLeft = list.scrollLeft + list.clientWidth * count;
        this.change.emit(this.getPagingInfo())
    }

    autoCompleteBlank() {
        const list = this.element.nativeElement.querySelector("[list]");
        const needWidth = list && (list.clientWidth - (list.clientWidth % list.clientWidth));
        const black = this.element.nativeElement.querySelector("[blank]");
        black && (black.style.width = needWidth + "px");
    }

    private getPagingInfo() {
        const list = this.element.nativeElement.querySelector("[list]");
        const items = this.element.nativeElement.querySelectorAll("[item]");
        if (!list || !items) {
            return;
        }
        const itemsAyyay = Array.from(items);
        let previousCount = 0;
        let nextCount = 0;
        const listOffsetLeft = list.offsetLeft;
        const listScrollLeft = list.scrollLeft;
        const listClientWidth = list.clientWidth;
        itemsAyyay.forEach(item => {
            const offsetLeft = (<any>item).offsetLeft - listOffsetLeft;
            if (offsetLeft < listScrollLeft) {
                previousCount++
            } else if (offsetLeft >= listScrollLeft + listClientWidth) {
                nextCount++;
            }
        })
        return {
            previousCount, nextCount, turningPage: this.turningPage.bind(this)
        }
    }
}



export interface pagingMessage {
    previousCount: number;
    nextCount: number;
    turningPage(count)
}


